<?php
//Load the database connection.

class Database
{
	var $conn;
	
	private $host = 'localhost';
	private $user = 'root';
	private $pass = '';
	private $db = 'photosaic';

	/*connect to database if possible*/
	function __construct()
	{
		$conn = mysql_connect($this->host,$this->user,$this->pass)
						or trigger_error("Error connecting to database!",E_USER_ERROR);
		$this->conn = $conn;
		mysql_select_db($this->db,$this->conn) or die("Error selecting database!");
	}
	
	/*
	query_read($sql)
	
	$sql - Query to be executed. Make sure to validate!
	
	Returns the query object, to be used with fetch_array().
	*/
	function query_read($sql)
	{
		//leave validation for the caller to do
		$qry = mysql_query($sql,$this->conn) or trigger_error("Error reading: ".mysql_error(),E_USER_ERROR);
		return $qry;
	}
	
	/*
	query_write($sql)
	
	$sql - Query to be executed.
	
	Returns the query object, in case it's needed.
	*/
	function query_write($sql)
	{
		$qry = mysql_query($sql,$this->conn) or trigger_error("Error writing: ".mysql_error(),E_USER_ERROR);
		return $qry;
	}
	
	/*
	fetch_array($qry)
	
	$qry - mysql query object to be used
	
	Returns an array of the next row returned by the query.
	*/
	function fetch_array($qry)  //in case a different database is used, the code
	{							//base won't have to be changed, just this file.
		return mysql_fetch_assoc($qry);
	}
	
	/*
	clean($str)
	
	$str - string to clean
	
	Returns a mysql-safe string. Like addslashes, but more mysql-itized.
	*/
	function clean($str)
	{
		return mysql_real_escape_string($str);
	}
	
	/*
	last_insert_id()
	
	Returns last inserted row's primary ID.
	*/
	function last_insert_id()
	{
		return mysql_insert_id($this->conn);
	}
	
	/**
	 * Return the number of results in a query.
	 *
	 * @param resource $qry
	 */
	function rows($qry)
	{
		return mysql_num_rows($qry);
	}
	
	/*
	row_count($table_name)
	
	$table_name - name of table to count rows of
	
	Returns number of rows in table. Useful for pagination.
	*/
	function row_count($table_name)
	{
		$sql = "SELECT COUNT(*) as count FROM `".$this->clean($table_name)."`";
		$qry = $this->query_read($sql);
		if ($row = $this->fetch_array($qry))
		{
			return $row['count'];
		}
		else
		{//table not found or something, will probably throw an error anyway
			return 0;
		}
	}	
}



?>